import Toast from 'wxcomponents/vant/toast/toast'

class RequestApi {
  constructor() {

  }

  // 本地
  // url = 'https://wdsw.c'

  // 测试
  url = 'https://tdt.qwtjt.com'
  // 生产
  // url = 'https://tdt.qwtjt.com'

  request(params, path) {
    return new Promise((resolve, reject) => {
      const {
        token,
        ...data
      } = params

      uni.request({
        url: this.url + path,
        data: data,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'token': token || ''
        },
        method: 'POST', 
        dataType: 'json',
        responseType: 'text',
        timeout: 60000,
        success: (res) => {
          if (res.data.code === 401) {
            Toast.clear()
            Toast('未登录,请重试')
            uni.clearStorageSync('token');
            const app = getApp()
            app.handleLogin()
            return reject(res)
          }
          if (res.code === 403) {
            Toast.clear()
            Toast('权限不足')
            return reject(res)
          }
          if (res.code === 500) {
            Toast.clear()
            Toast('服务器错误')
            return reject(res)
          }
          resolve(res.data)
        },
        fail: (err) => {
          Toast.clear()
          Toast('请求超时')
          reject(err)
        }
      });

    });
  }

  // 上传文件
  upload(tempFilePath, params, path) {
    return new Promise((resolve, reject) => {
      const {
        token,
        ...data
      } = params

      uni.uploadFile({
        url: this.url + path, //接口地址
        filePath: tempFilePath,
        name: 'file',
        formData: data,
        timeout: 60000,
        header:{
          'Content-Type': 'application/x-www-form-urlencoded',
          'token': token || ''
        },
        success(res) {
          resolve(JSON.parse(res.data))
        },
        fail: (err) => {
          Toast('请求超时')
          reject(err);
        }
      })
    });
  }

}

let requestApi = new RequestApi();

export default requestApi;